package com.example.forum.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.forum.commons.tools.StringUtil;
import com.example.forum.entity.*;
import com.example.forum.mapper.*;
import com.example.forum.service.ITAppuserService;
import com.example.forum.vo.DoAppoint;
import com.example.forum.vo.JsonResult;
import com.example.forum.vo.PageDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author why
 * @since 2020-04-22
 */
@Service
public class TAppuserServiceImpl extends ServiceImpl<TAppuserMapper, TAppuser> implements ITAppuserService {
    @Autowired
    TRegionMapper regionMapper;

    @Autowired
    TStreetMapper streetMapper;

    @Autowired
    TJuweiMapper juweiMapper;

    @Autowired
    private TAppuserMapper appuserMapper;

    @Autowired
    private TUsersMapper usersMapper;

    @Autowired
    private TRolesMapper rolesMapper;


    @Override
    public PageDto getAppointList(Integer pageIndex, Integer pageSize, String nameOrPhone, String appointStatus, Integer day2, String streetId, String neighborhoodCommitteeId) {

        DateTime date=null;
        DateTime offset=null;
        if (day2 != null) {
            //时间范围
            date = DateUtil.date(Calendar.getInstance());
            offset = DateUtil.offset(date, DateField.DAY_OF_MONTH, -day2);
        }
        //数目
        List<TAppuser> appointList = appuserMapper.getAppointListNum(nameOrPhone, appointStatus, offset, date);
        //分页
        List<TAppuser> appointList1 = appuserMapper.getAppointList(pageIndex, pageSize, nameOrPhone, appointStatus, offset, date,streetId,neighborhoodCommitteeId);

        return new PageDto((long) appointList.size(), appointList1);
    }

    @Override
    public boolean addUserWarningCount(String userId) {
        TAppuser appuser = getById(userId);
        appuser.setWarningcount(appuser.getWarningcount()+1);
        return updateById(appuser);
    }

    @Transactional
    @Override
    public JsonResult daAppointUser(DoAppoint doAppoint, String currentUserId) {
        //当前用户id  currentUserId
        String AppUserId = doAppoint.getAppUserId();
        //AppointStatus  1:委任  2:撤销
        Integer AppointStatus = doAppoint.getAppointStatus();
        //Role  用户角色名
        String Role = doAppoint.getRole();

        TAppuser appUserById = appuserMapper.selectOne(new QueryWrapper<TAppuser>()
                .eq("IsDeleted", 0)
                .eq("ID", AppUserId));
        if (appUserById == null) {
            return new JsonResult(HttpStatus.BAD_REQUEST, "该用户不存在", null);
        }
        // 是否存在用户名相同且AppointStatus==1的已经委任的用户
//        TAppuser one = appuserMapper.selectOne(new QueryWrapper<TAppuser>()
//                .eq("userName", appUserById.getUsername())
//                .eq("AppointStatus", 1)
//                .eq("IsDeleted", 0));
//        if (one != null) {
//            return new JsonResult(HttpStatus.BAD_REQUEST,"该用户名已经存在",null);
//        }
        if (AppointStatus == 1) {
            //如果没选角色名
            if (StringUtil.isEmpty(Role)) {
                return new JsonResult(HttpStatus.BAD_REQUEST, "未选择委任", null);
            }
            //修改APPuser表
            appUserById.setIsdeleted(false);
            appUserById.setAppointstatus(AppointStatus);
            appUserById.setAppointstr(Role);
            appUserById.setAppointerid(currentUserId);
            appuserMapper.updateById(appUserById);
            //修改用户表
            TUsers tUsers = new TUsers();
//            dataTransfer.getObjectFromObject(tUsers,appUserById);
            tUsers.setUsername(appUserById.getUsername());
            tUsers.setRealname(appUserById.getRealname());
            tUsers.setEmail(appUserById.getEmail());
            tUsers.setIsphonenumconfirmed(appUserById.getIsphonenumconfirmed());
            tUsers.setPhonenum(appUserById.getPhone());
            tUsers.setIsemailconfirmed(appUserById.getIsemailconfirmed());
            tUsers.setPassword(appUserById.getPassword());
            tUsers.setSalt(appUserById.getSalt());
            tUsers.setIslocked(appUserById.getIslocked());
            tUsers.setStreetid(appUserById.getStreetid());
            tUsers.setIdcard(appUserById.getIdcard());
            tUsers.setPeoplesex(appUserById.getGender());
            tUsers.setPeopleage(appUserById.getAge());
            //QR code 二维码
            tUsers.setPeoplecard(appUserById.getUserqrcode());
            tUsers.setPeoplepicture(appUserById.getPicture());
            tUsers.setPeopleintegration(appUserById.getIntegration());
            //用户来源  pc 0  被委托用户1  被委托取消用户2
            tUsers.setUsersource(1);
            tUsers.setRegionid(appUserById.getRegionid());
            tUsers.setNeighborhoodcommitteeid(appUserById.getNeighborhoodcommitteeid());
            tUsers.setAddress(appUserById.getAddress());
            tUsers.setIsdeleted(false);
            //驿站ID todo 未完成

            tUsers.setPoststationid("0000--0000");

            //插入  获取ID
            usersMapper.insert(tUsers);
            String userId = tUsers.getId();
            String roleId = rolesMapper.selectOne(new QueryWrapper<TRoles>().eq("name", Role)).getId();
            //向userRole表添加数据
            TUserroles tUserroles = new TUserroles();
            tUserroles.setIsdeleted(false);
            tUserroles.setUserid(userId);
            tUserroles.setRoleid(roleId);
            //角色ID封装到用户
            List<String> stringRoleId = new ArrayList<>();
            stringRoleId.add(roleId);
            tUsers.setRoles(stringRoleId);
            usersMapper.updateById(tUsers);
            //添加appuser表的pcuserid字段
            appUserById.setPcuserid(userId);
            appuserMapper.updateById(appUserById);
            return new JsonResult(HttpStatus.OK, "委任成功", null);
        } else {
            //删除user
            usersMapper.deleteById(appUserById.getPcuserid());
            //修改appuser
            appUserById.setAppointstatus(AppointStatus);
            appUserById.setId(AppUserId);
            appUserById.setAppointstr(Role);
            appuserMapper.updateById(appUserById);
            return new JsonResult(HttpStatus.OK, "撤销成功", null);
        }
    }



    @Override
    public void getUserAddress(TAppuser appuser) {
        TRegion region = regionMapper.selectById(appuser.getRegionid());
        TStreet street = streetMapper.selectById(appuser.getStreetid());
        TJuwei juwei = juweiMapper.selectById(appuser.getNeighborhoodcommitteeid());
        appuser.setRegionName(region.getName());
        appuser.setStreetName(street.getStreetname());
        appuser.setNeighborhoodCommitteeName(juwei.getName());
    }
}
